package org.budo.activiti.util;

import java.io.ByteArrayInputStream;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.budo.activiti.converter.BudoActivitiBpmnJsonConverter;
import org.budo.xml.Xml;
import org.budo.xml.XmlObject;

import com.fasterxml.jackson.databind.JsonNode;

/**
 * @author lmw
 * 
 * @see org.activiti.editor.language.json.converter.BaseBpmnJsonConverter#convertJsonToFormProperties
 */
public class BpmnModelUtil {
    public static String bpmnJsonToXml(byte[] modelEditorSource) {
        BpmnModel bpmnModel = bpmnJsonToModel(modelEditorSource);

        byte[] xmlBytes = bpmnModelToXml(bpmnModel);

        return xmlProcessNode(xmlBytes);
    }

    public static String xmlProcessNode(byte[] xmlBytes) {
        XmlObject xmlObject = Xml.parse(new ByteArrayInputStream(xmlBytes));

        XmlObject definitions = xmlObject.getChildNodeByName("definitions");
        XmlObject process = definitions.getChildNodeByName("process");
        return process.toString();
    }

    public static byte[] bpmnModelToXml(BpmnModel bpmnModel) {
        BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
        byte[] xmlBytes = bpmnXMLConverter.convertToXML(bpmnModel);
        return xmlBytes;
    }

    public static BpmnModel bpmnJsonToModel(byte[] modelEditorSource) {
        JsonNode modelNode = ObjectMapperUtil.readTree(modelEditorSource);
        BudoActivitiBpmnJsonConverter bpmnJsonConverter = new BudoActivitiBpmnJsonConverter();

        return bpmnJsonConverter.convertToBpmnModel(modelNode);
    }
}